import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:yurun_smartmerchants/global.dart';
import 'package:yurun_smartmerchants/interface/DialogInterface.dart';
import 'package:yurun_smartmerchants/models/pic_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/net/NetUtil.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/DialogUtil.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/utils/base64.dart';
import 'package:yurun_smartmerchants/utils/evenbus_utils.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/BaseDialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'personal_information_improvement.dart';

class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> implements DialogInterface {
  final _picker = ImagePicker();
  File _image;
  String name;
  String url;

  @override
  void initState() {
    super.initState();
    name = Global.prefs.getString(Global.merchantName);
    url = Global.prefs.getString(Global.url_avatar);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colours.mine_bg,
      width: double.infinity,
      height: double.infinity,
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: double.infinity,
              height: AppSize.height(300),
              decoration: new BoxDecoration(
                  color: Colours.app_main,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(AppSize.sp(24)),
                      bottomRight: Radius.circular(AppSize.sp(24)))),
              child: Stack(children: <Widget>[
                Container(
                  width: double.infinity,
                  height: AppSize.height(300),
                  decoration: new BoxDecoration(
                      color: Colours.app_main,
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(AppSize.sp(24)),
                          bottomRight: Radius.circular(AppSize.sp(24)))),
                  child: Stack(children: <Widget>[
                    GestureDetector(
                        onTap: () {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return _showNomalWid(context);
                              });
                        },
                        child: Container(
                          child: ClipOval(child: getImage()),
                          margin: EdgeInsets.only(
                              top: AppSize.sp(129), left: AppSize.sp(32)),
                        )),
                    Container(
                      child: Text(
                        name != null ? name : "张小文",
                        style: TextStyle(
                            fontSize: AppSize.sp(34), color: Colours.white),
                      ),
                      margin: EdgeInsets.only(
                          top: AppSize.sp(148), left: AppSize.sp(184)),
                    ),
                    Container(
                      child: GestureDetector(
                        child: Text(
                          "个人备案",
                          style: TextStyle(
                              fontSize: AppSize.sp(26),
                              color: Colours.mine_top_gary),
                        ),
                        onTap: () {
                          Navigator.pushNamed(
                              context, personal_information_page,arguments: 1);
                        },
                      ),
                      margin: EdgeInsets.only(
                          top: AppSize.sp(207), left: AppSize.sp(184)),
                    ),
                    Container(
                      color: Colours.mine_top_line,
                      width: AppSize.width(1),
                      height: AppSize.height(24),
                      margin: EdgeInsets.only(
                          top: AppSize.sp(215), left: AppSize.sp(315)),
                    ),
                    Container(
                      child: GestureDetector(
                        child: Text(
                          "企业备案",
                          style: TextStyle(
                              fontSize: AppSize.sp(26),
                              color: Colours.mine_top_gary),
                        ),
                        onTap: () {
                          Navigator.pushNamed(
                              context, enterprise_page);
                        },
                      ),
                      margin: EdgeInsets.only(
                          top: AppSize.sp(207), left: AppSize.sp(347)),
                    ),
                  ]),
                )
              ]),
            ),
            Container(
              margin: EdgeInsets.only(top: AppSize.sp(20)),
              height: AppSize.height(98),
              width: double.infinity,
              color: Colours.white,
              child: Stack(
                children: <Widget>[
                  Container(
                    child: Image.asset(
                      'images/mine_money_account.png',
                      width: AppSize.width(38),
                      height: AppSize.height(38),
                    ),
                    padding: EdgeInsets.only(left: AppSize.sp(32)),
                    alignment: Alignment.centerLeft,
                  ),
                  Container(
                    child: Text(
                      "资金账户",
                      style: TextStyle(
                          fontSize: AppSize.sp(28), color: Colours.gray_33),
                    ),
                    padding: EdgeInsets.only(left: AppSize.sp(103)),
                    alignment: Alignment.centerLeft,
                  ),
                  Container(
                    child: Text(
                      "未绑定",
                      style: TextStyle(
                          fontSize: AppSize.sp(27), color: Colours.app_main),
                    ),
                    padding: EdgeInsets.only(right: AppSize.sp(57)),
                    alignment: Alignment.centerRight,
                  ),
                  Container(
                    child: Image.asset(
                      'images/mine_arrow.png',
                      width: AppSize.width(11),
                      height: AppSize.height(23),
                    ),
                    padding: EdgeInsets.only(right: AppSize.sp(32)),
                    alignment: Alignment.centerRight,
                  ),
                ],
              ),
            ),
            GestureDetector(
                onTap: () {
                  DialogUtil.d.showAnimation(
                      context, "400-1539-198", "拨打", 200, false, this);
                },
                child: Container(
                  margin: EdgeInsets.only(top: AppSize.sp(1)),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  child: Stack(
                    children: <Widget>[
                      Container(
                        child: Image.asset(
                          'images/mine_contact_customer.png',
                          width: AppSize.width(38),
                          height: AppSize.height(38),
                        ),
                        padding: EdgeInsets.only(left: AppSize.sp(32)),
                        alignment: Alignment.centerLeft,
                      ),
                      Container(
                        child: Text(
                          "联系客服",
                          style: TextStyle(
                              fontSize: AppSize.sp(28), color: Colours.gray_33),
                        ),
                        padding: EdgeInsets.only(left: AppSize.sp(103)),
                        alignment: Alignment.centerLeft,
                      ),
                      Container(
                        child: Text(
                          "400-1539-198",
                          style: TextStyle(
                              fontSize: AppSize.sp(27), color: Colours.gray_33),
                        ),
                        padding: EdgeInsets.only(right: AppSize.sp(57)),
                        alignment: Alignment.centerRight,
                      ),
                    ],
                  ),
                )),
            GestureDetector(
                onTap: () {
                  Navigator.pushNamed(context, mine_setup_page);
                },
                child: Container(
                  margin: EdgeInsets.only(top: AppSize.sp(18)),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  child: Stack(
                    children: <Widget>[
                      Container(
                        child: Image.asset(
                          'images/mine_set.png',
                          width: AppSize.width(38),
                          height: AppSize.height(38),
                        ),
                        padding: EdgeInsets.only(left: AppSize.sp(32)),
                        alignment: Alignment.centerLeft,
                      ),
                      Container(
                        child: Text(
                          "设置",
                          style: TextStyle(
                              fontSize: AppSize.sp(28), color: Colours.gray_33),
                        ),
                        padding: EdgeInsets.only(left: AppSize.sp(103)),
                        alignment: Alignment.centerLeft,
                      ),
                      Container(
                        child: Image.asset(
                          'images/mine_arrow.png',
                          width: AppSize.width(11),
                          height: AppSize.height(23),
                        ),
                        padding: EdgeInsets.only(right: AppSize.sp(32)),
                        alignment: Alignment.centerRight,
                      ),
                    ],
                  ),
                ))
          ]),
    );
  }

  @override
  void sumit() {
    // TODO: implement sumit
    launch('tel:4001539198');
  }

  Image getImage() {
    return url != null
        ? Image.network(url,
            width: AppSize.width(120),
            height: AppSize.height(100),
            fit: BoxFit.cover)
//    Image.file(
//            _image,
//            width: AppSize.width(120),
//            height: AppSize.height(100),
//            fit: BoxFit.cover,
//          )
        : Image.asset(
            'images/mine_head.png',
            width: AppSize.width(120),
            height: AppSize.height(120),
          );
  }

  Widget _showNomalWid(BuildContext context) {
    return new Container(
        height: AppSize.height(200),
        child: Column(
          children: <Widget>[
            GestureDetector(
                onTap: () {
                  getPic();
                },
                child: Container(
                  child: Text("拍照"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                )),
            Container(
              height: AppSize.height(1),
              width: double.infinity,
              color: Colours.color_dcdcdc,
            ),
            GestureDetector(
                onTap: () {
                  getLocalPic();
                },
                child: Container(
                  child: Text("相册"),
                  height: AppSize.height(98),
                  width: double.infinity,
                  color: Colours.white,
                  alignment: Alignment.center,
                ))
          ],
        ));
  }

  Future getPic() async {
    PickedFile image = await _picker.getImage(source: ImageSource.camera);
    if (image != null) {
      File croppedFile = await ImageCropper.cropImage(
        sourcePath: image.path,
        maxWidth: 512,
        maxHeight: 512,
      );
      _image = File(image.path);
      handlePic(croppedFile);
    }
    Navigator.of(context).pop();
  }

  Future getLocalPic() async {
    PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    if (image != null) {
      File croppedFile = await ImageCropper.cropImage(
        sourcePath: image.path,
        maxWidth: 512,
        maxHeight: 512,
      );
      _image = File(image.path);
      handlePic(croppedFile);
    }
    Navigator.of(context).pop();
  }

  void handlePic(File image) {
    String fileName = image.path
        .substring(image.path.lastIndexOf('/') + 1, image.path.length)
        .toString();
    String ext = image.path
        .substring(image.path.lastIndexOf('.') + 1, image.path.length)
        .toString();
    Base64Tool.imageBase64(image.path).then((base64Str) {
      uploadImage(base64Str, ext, fileName);
    });
  }

  void uploadImage(String files, String ext, String fileName) {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.uploadPublicImage(files, ext, fileName).then((data) {
      PicEntity picEntity = PicEntity.fromJson(data);
      setState(() {
        url = picEntity.content[0].path;
      });
      //保存到本地
      Global.prefs.setString(Global.url_avatar, url);
      //上传图片成功处理
      showToast("上传照片成功");
      getAccountUploadImg(url);
      //绑定到账号
    }).catchError((onError) {
      setState(() {});
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  void getAccountUploadImg(String url) {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.getAccountUploadImg(url).then((value) {
      setState(() {});
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }
}
